package com.hcbd.tdwt.ui.xingyu.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import com.hcbd.tdwt.R;
import com.pancoit.compression.ZDCompression;

import com.hcbd.tdwt.base.AuthManger;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.ImgSendManager;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.FileUtil;
import com.hcbd.tdwt.util.FileUtils;
import com.hcbd.tdwt.view.CropImageView;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.MessageFormat;
import java.util.Timer;
import java.util.TimerTask;



@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_pictrue_view)
public class PictureViewActivity extends BaseActivity{
    @ViewById(R.id.quiteIV)
    ImageView quiteIV;
    @ViewById(R.id.cropImage)
    CropImageView cropImageView;
    @ViewById(R.id.sendBtn)
    Button sendBtn;
    @ViewById(R.id.sb_normal)
    SeekBar sbNormal;
    @ViewById(R.id.zoom_seek)
    SeekBar zoomSeek;
    @ViewById(R.id.compressionLevel)
    TextView compressionLevel;
    @ViewById(R.id.kbTips)
    TextView kbTips;
    @ViewById(R.id.seekLL)
    LinearLayout seekLL;
    @ViewById(R.id.sendTips)
    TextView sendTips;
    @ViewById(R.id.watchTv)
    TextView watchTv;
    @ViewById(R.id.zoom_tv)
    TextView zoomTV;


    @ViewById(R.id.old_img)
    ImageView oldImg;

    @ViewById(R.id.zoom_img)
    ImageView zoomImg;
    @ViewById(R.id.crop_img)
    ImageView cropImg;
    @ViewById(R.id.topRL)
    RelativeLayout topRL;
    @ViewById(R.id.zipAreaLL)
    LinearLayout zipAreaLL;
    @ViewById(R.id.zoomAreaLL)
    LinearLayout zoomAreaLL;
    @ViewById(R.id.confirmAreaLL)
    LinearLayout confirmAreaLL;
    @ViewById(R.id.center_area)
    LinearLayout centerArea;
    @ViewById(R.id.zoomQuiteBtn)
    Button zoomQuiteBtn;
    @ViewById(R.id.zoomConfirmBtn)
    Button zoomConfirmBtn;
    @ViewById(R.id.cropConfirmBtn)
    Button cropConfirmBtn;
    @ViewById(R.id.cropQuiteBtn)
    Button cropQuiteBtn;
    @ViewById(R.id.widthAndHeight)
    TextView widthAndHeight;

    private int mProgress=0;

    private String path;
    private String saveFile;
    private String sendReminder;
    private String second;
    private int sendImgFreq;
    private String about;
    private String compressionLevelStr;
    private Bitmap imgBitmap;
    private Bitmap newBitMap;
    private String heightStr;
    private String widthStr;
    private int width;
    private int height;

    public String[] strArray=new String[]{"100kb","50kb","35kb","20kb","10kb"};
    public int[] strValue=new int[]{100,50,35,20,10};
    private Timer timer;
    private TimerTask task;
    public final static int FOUR_LEVEL_CARD_BYTE=900;
    public final static int FIVE_LEVEL_CARD_BYTE=1600;

    //开启定时器
    public  void startTime() {
        if(timer==null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    if(BeidouBoxParams.sentWaitSec>0){
                        msg.what = 1;
                        refreshHandler.sendMessage(msg);
                    }else{
                        msg.what =2;
                        refreshHandler.sendMessage(msg);
                        if(timer!=null){
                            timer.cancel();
                        }
                        if(task!=null){
                            task.cancel();
                        }
                    }
                }
            };
            timer.schedule(task, 1000, 1000);
        }
    }

    public void refreshStatus(){
        String kb=strArray[mProgress];
        int kbValue=strValue[mProgress];
        sendTips.setText(MessageFormat.format("{0}{1} {2}", sendReminder, kbValue * sendImgFreq, second));
        kbTips.setText(String.format("%s%s", about, kb));
    }

    @AfterViews
    protected void init() {

        sbNormal.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                compressionLevel.setText(MessageFormat.format("{0}:{1}", compressionLevelStr, (progress+1)));
                mProgress=progress;
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                refreshStatus();
            }
        });
        zoomSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                zoomTV.setText(String.format("%s%%", progress * 10));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                scaleBitmap(seekBar.getProgress());
            }
        });
        initData();
    }




    protected void initData() {
        sendReminder=getString(R.string.estimated_delivery_time)+" ";
        second=getString(R.string.second)+" ";
        sendImgFreq=BeidouBoxParams.sendFreq + 4;
        about=getString(R.string.about)+" ";
        compressionLevelStr=getString(R.string.compression_level);
        widthStr=getString(R.string.width);
        heightStr=getString(R.string.height);
        path=getIntent().getStringExtra("path");
        imgBitmap= BitmapFactory.decodeFile(path);
        minWidth =imgBitmap.getWidth()/10;
        minHeight=imgBitmap.getHeight()/10;
        width=imgBitmap.getWidth();
        height=imgBitmap.getHeight();
        newBitMap=imgBitmap;//裁剪后原图片
        zoomBitmap=imgBitmap;//等比压缩后原图片
        sbNormal.setProgress(4);
        scaleBitmap(0);
        if(BeidouBoxParams.cardType==5){
            sendBdByte=FIVE_LEVEL_CARD_BYTE;
        }
        refreshStatus();
        if(BeidouBoxParams.sentWaitSec>0){
            sendBtn.setEnabled(false);
            startTime();
        }
    }
    @Click
    void quiteIV(){
        finish();
    }
    public void quiteBtn(){
        zoomAreaLL.setVisibility(View.GONE);//缩放
        cropImageView.setVisibility(View.GONE);//裁剪框
        confirmAreaLL.setVisibility(View.GONE);//底部确认部分
        oldImg.setVisibility(View.VISIBLE);//原图
        topRL.setVisibility(View.VISIBLE);//顶部
        zipAreaLL.setVisibility(View.VISIBLE);
        centerArea.setVisibility(View.VISIBLE);//间部
        zoomSeek.setProgress(0);
        oldImg.setImageBitmap(newBitMap);
    }
    @Click
    public void cropConfirmBtn(){
        try {
            newBitMap = cropImageView.getCropImage();
            oldImg.setImageBitmap(newBitMap);
            quiteBtn();
        }catch (Exception e){
            e.printStackTrace();
            toast("裁减区域有误,请调整裁剪框!");
        }

    }
    public boolean ImageMinLimit(){
        if(300>newBitMap.getWidth()||300>newBitMap.getHeight()){
            toast("当前图片过小,无法裁剪！");
            return false;
        }
        return true;
    }

    @Click(R.id.crop_img)
    public void cropImg(){
        if(!ImageMinLimit()){
            return;
        }
        oldImg.setVisibility(View.GONE);//原图
        topRL.setVisibility(View.GONE);//顶部
        zoomAreaLL.setVisibility(View.GONE);//等比缩放
        centerArea.setVisibility(View.GONE);//中间部
        zipAreaLL.setVisibility(View.GONE);
        confirmAreaLL.setVisibility(View.VISIBLE);//显示底部确认部分
        cropImageView.setVisibility(View.VISIBLE);//显示裁剪框
        BitmapDrawable bd=new BitmapDrawable(newBitMap);

        cropImageView.setDrawable(bd,bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
    }
    @Click(R.id.zoom_img)
    public void zoomImg(){
        if(!ImageMinLimit()){
            return;
        }
        topRL.setVisibility(View.GONE);//隐藏顶部
        cropImageView.setVisibility(View.GONE);//隐藏裁剪框
        confirmAreaLL.setVisibility(View.GONE);
        zipAreaLL.setVisibility(View.GONE);
        centerArea.setVisibility(View.GONE);//隐藏中间部
        oldImg.setImageBitmap(newBitMap);
        zoomAreaLL.setVisibility(View.VISIBLE);//等比缩放
        zoomBitmap=newBitMap;
        width=newBitMap.getWidth();
        height=newBitMap.getHeight();
        minWidth =newBitMap.getWidth()/10;
        minHeight=newBitMap.getHeight()/10;
        widthAndHeight.setText(MessageFormat.format("{0}{1} {2}{3}", widthStr,newBitMap.getWidth(), heightStr,newBitMap.getHeight()));
    }
    @Click
    public void zoomQuiteBtn(){
        quiteBtn();
    }
    @Click
    public void cropQuiteBtn(){
        quiteBtn();
    }
    @Click
    public void zoomConfirmBtn(){
        newBitMap=zoomBitmap;
        quiteBtn();
    }

    public int minHeight;
    public int minWidth;
    private Bitmap zoomBitmap;
    public void scaleBitmap(int progress){
        zoomBitmap= FileUtils.createScaleBitmap(newBitMap,width-(progress*minWidth),height-(progress*minHeight));
        widthAndHeight.setText(MessageFormat.format("{0}{1} {2}{3}", widthStr,zoomBitmap.getWidth(), heightStr,zoomBitmap.getHeight()));
        oldImg.setImageBitmap(zoomBitmap);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        freeBitmap(imgBitmap);
    }
    private void freeBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            bitmap.recycle();
        }
    }
    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler refreshHandler = new Handler() {
        @Override
        public void handleMessage( Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SEND_CODE:
                    hideLoading();
                    if (ImgSendManager.getInstance().pIcZipList == null) {
                        toast("图片异常,发送失败!");
                        return;
                    }
                    Intent intent=new Intent();
                    intent.putExtra("saveFile",saveFile);
                    setResult(RESULT_OK,intent);
                    finish();
                    break;
                case BTN_STATUS_CODE_ONE:
                    sendBtn.setText(MessageFormat.format("{0}s", BeidouBoxParams.sentWaitSec));
                    break;
                case BTN_STATUS_CODE_TWO:
                    sendBtn.setText("发送");
                    sendBtn.setEnabled(true);
                    break;

            }
        }
    };
    private final int SEND_CODE=5;
    public  final int BTN_STATUS_CODE_ONE=6;
    public  final int BTN_STATUS_CODE_TWO=7;
    private int sendBdByte=FOUR_LEVEL_CARD_BYTE;
    @Click
    public void sendBtn(){
        if(!BeidouBoxParams.isBoxConnectNormal){
            toast("连接已断开,请重新连接!");
            return;
        }
        showLoading(getString(R.string.is_connected));
        int index=sbNormal.getProgress();
        final int number=strValue[index];
        new Thread(() -> {
            saveFile = FileUtil.getSendImgFile()+"send"+ DateUtils.getDateShortSerial()+".jpg";
            int bitWidth = newBitMap.getWidth();
            int bitHeight = newBitMap.getHeight();
            FileUtils.saveBitmapFile(newBitMap, saveFile);
            if(AuthManger.getAuthManger().isPicOnline()) {
                ImgSendManager.getInstance().pIcZipList = ZDCompression.getInstance().encoderImage(saveFile, 40, true, bitWidth, bitHeight, sendBdByte, sendBdByte, number * sendBdByte);
            }else{
                ImgSendManager.getInstance().pIcZipList = ZDCompression.getInstance().off_img_zip(saveFile, 40, true, bitWidth, bitHeight, sendBdByte, sendBdByte, number * sendBdByte);
            }
            Message msg = new Message();
            msg.what = SEND_CODE;
            refreshHandler.sendMessage(msg);
        }).start();
    }

}
